package com.zhou.service.impl.event;


import com.zhou.configure.PushConfigure;
import com.zhou.dto.IdentityInfo;
import com.zhou.dto.ResponseMessage;
import com.zhou.enums.WxMessageType;
import com.zhou.repository.IdentityInfoDataRepository;
import com.zhou.service.WxEventStrategy;
import com.zhou.utils.WxOpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author lcz
 * @desc 订阅策略
 * @mail lcz_0130@163.com
 * @date 2023/12/28
 */

@Service("subscribe")
@Slf4j
public class SubscribeStrategy implements WxEventStrategy {
    @Resource
    private PushConfigure pushConfigure;
    @Resource
    private IdentityInfoDataRepository identityInfoDataRepository;

    @Override
    public void execute(Map<String, String> requestMap, HttpServletResponse response) throws Exception {
        log.info("事件类型：subscribe");
        // 获取订阅者基本信息
        IdentityInfo identityInfoInformation = getWxSubscriber(requestMap);
        log.info("新用户订阅！");
        // 用户关注后返回信息
        String returnContent = "感谢关注！" + System.lineSeparator() + "请开启地理位置已获取天气服务，发送位置也可获取天气服务。" + System.lineSeparator() + "功能完善中，敬请期待~";
        // 发送方账号
        String openId = requestMap.get("FromUserName");
        // 公众号
        String publicId = requestMap.get("ToUserName");
        ResponseMessage responseMessage = new ResponseMessage();
        responseMessage.setFromUserName(publicId);
        responseMessage.setToUserName(openId);
        responseMessage.setMsgType(WxMessageType.TEXT.getType());
        responseMessage.setCreateTime(System.currentTimeMillis());
        responseMessage.setContent(returnContent);
        WxOpUtils.returnMessages(response, responseMessage);

        // 查询数据库里是否有该订阅者的信息
        IdentityInfo infoFromDataBase = identityInfoDataRepository.findByOpenId(openId);
        // 如果没有该订阅者信息则更新，有该订阅者信息则跳过（数据库中的信息可能包括更精确的经纬度信息）
        if (infoFromDataBase != null) {
            // 如果是取消关注重新关注的时候，需要更新status为0
            infoFromDataBase.setUserStatus(0);
            identityInfoDataRepository.save(infoFromDataBase);
            return;
        }
        IdentityInfo identityInfo = new IdentityInfo();
        identityInfo.setAppId(identityInfoInformation.getAppId());
        identityInfo.setAppSecret(identityInfoInformation.getAppSecret());
        identityInfo.setOpenId(openId);
        identityInfo.setPublicId(publicId);
        identityInfoDataRepository.save(identityInfo);
    }

    /**
     * 得到wx订阅者
     *
     * @param requestMap 请求映射
     * @return {@link IdentityInfo}
     */
    public IdentityInfo getWxSubscriber(Map<String, String> requestMap) {
        // 发送方账号
        String openId = requestMap.get("FromUserName");
        // 公众号
        String officialAccount = requestMap.get("ToUserName");
        IdentityInfo identityInfo = new IdentityInfo();
        identityInfo.setAppId(pushConfigure.getAppId());
        identityInfo.setAppSecret(pushConfigure.getSecret());
        identityInfo.setOpenId(openId);
        identityInfo.setPublicId(officialAccount);
        return identityInfo;
    }
}
